﻿package org.leles.aom 
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.external.ExternalInterface;
	import org.leles.aom.events.ChannelEvent;
	import org.leles.aom.objects.Channel;
	import org.leles.aom.objects.Messenger;
	import org.leles.aom.objects.Users;
	/**
	 * ...
	 * @author Bruno Leles
	 */
	public class Activity extends EventDispatcher
	{
		private var driverId:String;
		
		public var initialized:Boolean;
		public var active:Boolean;
		
		private var _channel:Channel;
		private var _users:Users;
		private var _messenger:Messenger;
		
		public function Activity() 
		{
			super();
			
			initialized	= false;
			active		= false;
			
			initialize();
		}
		
		private function createJavascriptDriver():void 
		{
			if ( !ExternalInterface.available ) return;
			driverId = ExternalInterface.call("Core.CreateDriver", ExternalInterface.objectID );
			//if( TestView.instance )TestView.instance.trace2( driverId );
		}
		
		public function initialize():void 
		{
			if ( initialized ) return;
			
			createJavascriptDriver();
			
			ExternalInterface.addCallback("DispatchEvent2", dispatchEvent2);
			
			_channel	= new Channel(this);
			_users		= new Users(this);
			_messenger	= new Messenger(this);
			
			initialized	= true;
		}
		
		private function dispatchEvent2(type:String, data:*):void
		{
			var event:Event;
			switch (type) 
			{
				case ChannelEvent.DATA_ERROR:
				case ChannelEvent.DATA_RECEIVED:
				case ChannelEvent.FILE_PROGRESS:
				case ChannelEvent.FILE_RECEIVED:
				case ChannelEvent.IM_RECEIVED:
				case ChannelEvent.REMOTE_APP_CLOSED:
				case ChannelEvent.REMOTE_APP_LOADED:
				case ChannelEvent.SENDFILE_CANCELLED:
				case ChannelEvent.TYPE_CHANGED:
					ChannelEvent(event = new ChannelEvent(type, false, false) ).loadEventData(data);
					_channel.dispatchEvent(event);
					break;
			}
		}
		
		public function activate():void 
		{
			if ( active ) return;
			active = true;
		}
		
		public function callDriverMethod(method:String, parms:Array = null, responseAs:Class = null):* 
		{
			return callMethod( 'Core.Drivers.CallDriverMethod', [driverId, method , parms], responseAs );
		}
		
		public function callMethod(method:String, parms:Array = null, responseAs:Class = null):*
		{
			parms.unshift( method );
			var response:*;
			var rawResponse = ExternalInterface.call.apply(null, parms);
			if ( responseAs != null )
			{
				response = new responseAs();
			}
			else
			{
				response = rawResponse;
			}
			
			return response;
		}
		
		public function get channel():Channel { return _channel; }
		
		public function get users():Users { return _users; }
		
		public function get messenger():Messenger { return _messenger; }
	}

}